package com.raos.example.redis.networkmodel.reactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 单线程Reactor 模型（高性能I/O设计模式）
 * 连接请求处理授体
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/7/23 23:32
 **/
public class Acceptor implements Runnable {

    /**
     * 连接通道的多路复用器
     */
    private final Selector selector;

    /**
     * 面向流监听套接字的可选通道
     */
    private final ServerSocketChannel serverSocketChannel;

    /**
     * 有参构造
     */
    public Acceptor(Selector selector, ServerSocketChannel serverSocketChannel) {
        this.selector = selector;
        this.serverSocketChannel = serverSocketChannel;
    }

    @Override
    public void run() {
        SocketChannel channel;
        try {
            //得到一个客户端连接
            channel = serverSocketChannel.accept();
            System.out.println(channel.getRemoteAddress() + ":收到一个客户端连接");
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ, new Handler(channel));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
